<template>
  <div class="inventory-management">
    <header class="header">
      <div class="title-and-button-container">
        <h1 class="page-title">资源库存管理</h1>
        <!-- 新增库存按钮 -->
        <el-button type="primary" @click="dialogVisible = true" class="add-inventory-btn">新增库存</el-button>
      </div>
    </header>

    <!-- 新增库存对话框 -->
    <el-dialog title="新增库存" :visible.sync="dialogVisible" width="50%">
        <el-form :model="newItem" label-width="120px" class="add-inventory-form">
          <el-form-item label="资源名称">
            <el-select 
              v-model="newItem.materialId" 
              placeholder="请选择资源"
              @change="fetchSupplierInfo"
            >
              <el-option 
                v-for="item in resourceOptions" 
                :key="item.materialId" 
                :label="item.name"
                :value="item.materialId">
              </el-option>
            </el-select>
          </el-form-item>
        <el-form-item label="库存数量">
          <el-input-number v-model="newItem.quantity" :min="0"></el-input-number>
        </el-form-item>
        <el-form-item label="供应商名称">
          <el-input v-model="newItem.supplier.name" placeholder="请输入供应商名称"></el-input>
        </el-form-item>
        <el-form-item label="联系人姓名">
          <el-input v-model="newItem.supplier.contactPerson" placeholder="请输入联系人姓名"></el-input>
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="newItem.supplier.phone" placeholder="请输入联系电话"></el-input>
        </el-form-item>
        <el-form-item label="电子邮件">
          <el-input v-model="newItem.supplier.email" placeholder="请输入电子邮件地址"></el-input>
        </el-form-item>
        <el-form-item label="地址">
          <el-input type="textarea" v-model="newItem.supplier.address" placeholder="请输入地址"></el-input>
        </el-form-item>
        <el-form-item label="其他信息">
          <el-input type="textarea" v-model="newItem.supplier.additionalInfo" placeholder="请输入其他信息"></el-input>
        </el-form-item>
        <el-form-item label="采购人">
          <el-input v-model="newItem.purchaser" placeholder="请输入采购人姓名"></el-input>
        </el-form-item>
      </el-form>
     <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addItem">确认添加</el-button>
        </span>
    </el-dialog>
  <!-- 物资详情对话框 -->
      <el-dialog title="物资详情" :visible.sync="detailDialogVisible" width="60%">
        <div v-if="selectedInventory && selectedInventory.supplier" class="details-container">
          <div class="section">
            <h3>基本信息</h3>
            <ul class="info-list">
              <li><strong>物资ID:</strong> {{ selectedInventory.materialId }}</li>
              <li><strong>资源名称:</strong> {{ selectedInventory.materialName }}</li>
              <li><strong>库存数量:</strong> {{ selectedInventory.currentQuantity }}</li>
              <li><strong>采购人:</strong> {{ selectedInventory.purchaser || '无' }}</li>
            </ul>
          </div>
          <div class="section">
            <h3>供应商信息</h3>
            <ul class="info-list">
              <li><strong>供应商名称:</strong> {{ selectedInventory.supplier.name || '无' }}</li>
              <li><strong>联系人姓名:</strong> {{ selectedInventory.supplier.contactPerson || '无' }}</li>
              <li><strong>联系电话:</strong> {{ selectedInventory.supplier.phone || '无' }}</li>
              <li><strong>电子邮件:</strong> {{ selectedInventory.supplier.email || '无' }}</li>
              <li><strong>地址:</strong> {{ selectedInventory.supplier.address || '无' }}</li>
              <li><strong>其他信息:</strong> {{ selectedInventory.supplier.additionalInfo || '无' }}</li>
            </ul>
          </div>
        </div>
        <p v-else>加载中...</p>
      </el-dialog>

      <!-- 库存列表 -->
      <section class="inventory-list-section">
      <el-table :data="inventory" style="width: 100%" class="inventory-table" border stripe @row-click="showDetail">
        <!-- 确保所有列都有默认值 -->
        <!-- <el-table-column prop="materialId" label="物资ID" align="center"></el-table-column> -->
        <el-table-column prop="materialName" label="资源名称" align="center"></el-table-column>
        <el-table-column prop="currentQuantity" label="库存数量" align="center"></el-table-column>
        <el-table-column label="供应商" align="center">
          <template slot-scope="scope">
            {{ scope.row.supplierName || '无' }}
          </template>
        </el-table-column>
        <el-table-column label="联系人" align="center">
          <template slot-scope="scope">
            {{ scope.row.contactPerson || '无' }}
          </template>
        </el-table-column>
        <el-table-column label="联系方式" align="center">
          <template slot-scope="scope">
            {{ scope.row.phone || '无' }}
          </template>
        </el-table-column>
        <el-table-column prop="purchaser" label="采购人" align="center"></el-table-column>
        <el-table-column label="库存状态" align="center" >
          <template slot-scope="scope" >
            <span :class="getStockStatus(scope.row.currentQuantity)">
              {{ getStockMessage(scope.row.currentQuantity) }}
            </span>
          </template>
        </el-table-column>
      </el-table>
    </section>
    </div>
</template>


<script>
import { mapState, mapActions } from 'vuex';

export default {
  computed: {
    ...mapState('inventory', ['inventory', 'resourceOptions', 'warningThreshold'])
  },
  methods: {
    ...mapActions('inventory', ['fetchInventory', 'addInventoryItem', 'fetchResourceOptions']),
    // 新增方法：根据物资ID获取供应商信息
    fetchSupplierInfo(materialId) {
      if (materialId) {
        const selectedResource = this.resourceOptions.find(option => option.materialId === materialId);
        if (selectedResource && selectedResource.supplier) {
          // 更新 newItem 中的供应商信息
          this.newItem.supplier = { ...selectedResource.supplier };
        }
      }
    },
   addItem() {
      if (this.newItem.materialId && this.newItem.quantity > 0 && this.newItem.supplier.name) {
        this.addInventoryItem(this.newItem)
          .then(() => {
            this.clearNewItem();
            this.dialogVisible = false;
            this.fetchInventory();
            this.fetchResourceOptions();
            // 成功提示
            this.$message({
              message: '增加库存信息成功',
              type: 'success'
            });
          })
          .catch(() => {
            alert('添加库存失败，请检查输入信息');
            // 或者使用更友好的提示方式
            // this.$message.error('添加库存失败，请检查输入信息');
          });
      } else {
        alert('请填写完整的库存信息');
        // 或者使用更友好的提示方式
        // this.$message.warning('请填写完整的库存信息');
      }
    },
   clearNewItem() {
      this.newItem = {
        materialId: '',
        quantity: 0,
        supplier: { name: '', contactPerson: '', phone: '', email: '', address: '', additionalInfo: '' },
        purchaser: ''
      };
    },
    getStockMessage(quantity) {
      return this.warningThreshold <= quantity ? '库存充足' : '库存告急！！';
    },
    getStockStatus(quantity) {
      return this.warningThreshold <= quantity ? '' : 'warning';
    },
    showDetail(row) {
      console.log('显示详情:', row);
      // 在显示详情之前检查row是否存在以及是否包含必要的信息
      if (row && row.materialId) {
        // 查找resourceOptions以获取完整的信息
        const selectedResource = this.resourceOptions.find(option => option.materialId === row.materialId);

        // 如果找到了对应的资源，则用其数据覆盖当前行的数据
        if (selectedResource) {
          this.selectedInventory = {
            materialId: row.materialId,
            materialName: selectedResource.name || '未知',
            currentQuantity: row.currentQuantity || selectedResource.quantity || 0,
            purchaser: selectedResource.purchaser || '无',
            supplier: {
              name: selectedResource.supplier?.name || '无',
              contactPerson: selectedResource.supplier?.contactPerson || '无',
              phone: selectedResource.supplier?.phone || '无',
              email: selectedResource.supplier?.email || '无',
              address: selectedResource.supplier?.address || '无',
              additionalInfo: selectedResource.supplier?.additionalInfo || '无'
            }
          };
        } else {
          this.selectedInventory = row;
        }

        this.detailDialogVisible = true;
      } else {
        console.error('无效的库存条目:', row);
        alert('无法显示此条目的详细信息，请检查数据完整性。');
      }
    }
  },
  created() {
    // 当组件创建时，加载库存和资源选项
    this.fetchInventory();
    this.fetchResourceOptions();
  },
  data() {
    return {
      newItem: {
        materialId: '',
        quantity: 0,
        supplier: { name: '', contactPerson: '', phone: '', email: '', address: '', additionalInfo: '' },
        purchaser: ''
      },
      dialogVisible: false, // 控制新增库存对话框显示/隐藏
      detailDialogVisible: false, // 控制物资详情对话框显示/隐藏
      selectedInventory: null // 初始化为null以确保在使用前检查
    };
  }
};
</script>
<style scoped>
.inventory-management {
  font-family: Arial, sans-serif;
}

.header {
  margin-bottom: 20px;
  padding-top: 30px;
  /* background-color: #f5f7fa; */
  /* border-bottom: 1px solid #dcdfe6; */
}

h1 {
  color: #303133;
  text-align: center;
  margin: 0;
}

.title-and-button-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-title {
  flex-grow: 1;
  text-align: center;
}

.add-inventory-btn {
  margin-right: 30px;
}

.inventory-table {
  width: 100%;
  margin-top: 20px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

/* 表格美化 */
.el-table th {
  background-color: #eef1f6;
  color: #303133;
  font-weight: bold;
  font-size: 14px;
  padding: 12px 16px;
  text-align: left;
  border-bottom: 1px solid #dcdfe6;
}

.el-table td {
  padding: 12px 16px;
  border-bottom: 1px solid #dcdfe6;
  text-align: left;
}

.el-table tr:nth-child(even) {
  background-color: #fafafa;
}

.el-table tr:hover {
  background-color: #f5f7fa;
  transition: background-color 0.3s ease;
}

.el-table .warning {
  font-size: larger;
  color: red;
}

/* 对话框样式 */
.el-dialog {
  border-radius: 10px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.2);
}

.add-inventory-form {
  max-width: 100%;
}

@media screen and (max-width: 600px) {
  .add-inventory-form {
    max-width: 100%;
  }

  .add-inventory-btn {
    margin-right: 10px;
  }
}

.details-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.section {
  background-color: #f5f7fa;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.section h3 {
  margin-top: 0;
  font-size: 1.2em;
  color: #303133;
}

.info-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.info-list li {
  margin-bottom: 10px;
  font-size: 1em;
}

.info-list li strong {
  font-weight: bold;
  color: #606266;
  margin-right: 10px;
}
</style>